<template>
  <div class="verification-code-page">
    <h2 style="margin-bottom: 20px;">验证码管理</h2>

    <!-- 查询区域 -->
    <el-row :gutter="10" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-select v-model="searchType" placeholder="请选择验证码类型进行筛选" @change="fetchData">
          <el-option
            v-for="(label, value) in filteredTypeOptions"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button-group>
          <el-button type="primary" @click="dialogVisible = true">生成验证码</el-button>
          <el-button type="info" @click="resetSearch">重置查询条件</el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <!-- 验证码列表 -->
    <VerificationCodeList
      :verification-codes="filteredCodes"
      @delete="handleDelete"
    />

    <!-- 创建验证码对话框 -->
    <el-dialog title="创建验证码" :visible.sync="dialogVisible" width="30%">
      <el-form>
        <el-form-item label="选择验证码类型">
          <el-select v-model="selectedType" placeholder="请选择验证码类型">
            <el-option
              v-for="(label, value) in filteredTypeOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createCode">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import VerificationCodeList from '../../components/admin/VerificationCodeList.vue';
import { mapState } from 'vuex';
export default {
  name: 'AdminVerificationCode',
  components: { VerificationCodeList },
  data() {
    return {
      codes: [],
      searchType: '',
      selectedType: '',
      dialogVisible: false,
      typeOptions: {
        ACTIVATION: '用户激活码',
        SUBMIT_ORDER: '普通订单验证码',
        SUPER_SUBMIT_ORDER: '高级订单验证码'
      }
    };
  },
  created() {
    this.fetchData();
    setInterval(() => {
        if (this.user.active&&this.$route.name=="VerificationCode") {
          this.fetchData();
        }
      }, 4000);
  },
  computed: {
    ...mapState(['user']),
    filteredTypeOptions() {
      // 如果是超级管理员，返回全部类型
      if (this.user && this.user.role=="SUPER_ADMIN") {
        return this.typeOptions;
      }
      // 普通管理员不能选择 ACTIVATION 类型
      const options = { ...this.typeOptions };
      delete options.ACTIVATION;
      return options;
    },
    filteredCodes() {
      // 如果是超级管理员，返回全部验证码
      if (this.user && this.user.role=="SUPER_ADMIN") {
        return this.codes;
      }
      // 普通管理员过滤掉 ACTIVATION 类型的验证码
      return this.codes.filter(code => code.type !== 'ACTIVATION');
    }
  },
  methods: {
    async fetchData() {
      try {
        let params = {};
        if (this.searchType) {
          params.type = this.searchType;
        }
        if (!this.user.active) {
          throw new Error('用户未激活');
        }
        const res = await axios.get('/api/admin/verificationCode/getVerificationCodeList', { params });
        if (res.data.code == 1) {
          this.codes = res.data.data;
        } else {
          this.$message.error(res.data.msg || '获取验证码失败');
        }
      } catch (err) {
        console.error('验证码获取失败', err);
      }
    },
    createCode() {
      if (!this.selectedType) {
        this.$message.warning('请选择验证码类型');
        return;
      }

      axios.post(`/api/admin/verificationCode/createCode/${this.selectedType}`)
        .then(res => {
          if (res.data.code == 1) {
            this.$message.success('验证码已生成');
            this.dialogVisible = false; // 关闭对话框
            this.fetchData(); // 刷新数据
          } else {
            this.$message.error(res.data.msg || '生成验证码失败');
          }
        })
        .catch(err => {
          this.$message.error('请求出错，请检查网络连接或接口地址：'+err);
        });
    },
    handleDelete(id) {
      this.$confirm('确定要删除该验证码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/admin/verificationCode/deleteById/${id}`)
          .then(res => {
            if (res.data.code == 1) {
              this.$message.success('删除成功');
              this.fetchData(); // 刷新数据
            } else {
              this.$message.error(res.data.msg || '删除失败');
            }
          })
          .catch(err => {
            this.$message.error('请求出错，请检查网络连接或接口地址:'+err);
          });
      }).catch(() => {
      });
    },
    resetSearch() {
      this.searchType = '';
      this.fetchData();
    }
  }
};
</script>

<style scoped>
.verification-code-page {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.el-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.el-button-group .el-button:not(:last-child) {
  margin-right: 10px;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

h2 {
  color: #333;
  font-weight: bold;
}
</style>